import $pig from '@daelui/pigjs'

// 部署
function deploy (config) {
  // 初始化模块配置
  const loader = config.loader || {}
  const domain = config.domain || location.origin
  const rootUrl = loader.rootUrl || location.origin
  const metaConf = config.meta || {}
  $pig.init({
    path: loader.path || '@daelui/pigjs/latest/dist/system.min.js',
    registry: loader.registry || domain + '/packages.json',
    rootUrl: rootUrl,
    rootUrls: loader.rootUrls,
    resolutions: [{name: 'vue', version: '2.*.*'}]
  }).then(function(){
    // 加载元数据
    return fetch(metaConf.app ||  './app.meta.json').then(res => {
      return res.json().then(app => {
        let appName = app.name
        let rootPath = app.path
        let routes = JSON.parse(app.meta)
        return { rootPath, routes, appName }
      })
    })
  }).then(({ rootPath, routes, appName }) => {
    // 加载渲染器
    $pig.import('./deploy/runtime/dist/runtime.umd.min.js').then(res => {
      const { bootstrap } = res
      bootstrap({
        appName: appName,
        routes: routes,
        rootPath: rootPath,
        config: metaConf,
        registryMap: $pig.registryMap
      })
    })
  })

  // 可替换标识符
  $pig.identifyMap = $pig.identifyMap || {}
  let identifyMap = config.identifyMap || {}
  $pig.identifyMap = Object.assign($pig.identifyMap, identifyMap)
  const rules = config.rules || []
  const host = rules.find(item => item.rule === 'host')
  if (host) {
    $pig.identifyMap.host = host.url
  }
}

$pig.deploy = deploy

export {
  deploy
}
